package com.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadLocalDemo {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");

    public static void main(String[] args) {
        new ThreadLocalDemo().threadPool();
    }

    public void threadPool() {
        for (int i = 0; i < 30; i++) {
            int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    String date = new ThreadLocalDemo().formatDate(finalI);
                    System.out.println(Thread.currentThread().getName() + "-" + date);
                }
            });
        }
        threadPool.shutdown();
    }

    /**
     * 使用单线程
     */
    public void threadLocal() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String date = new ThreadLocalDemo().formatDate(10);
                System.out.println(Thread.currentThread().getName() + "-" + date);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String date = new ThreadLocalDemo().formatDate(12780);
                System.out.println(Thread.currentThread().getName() + "-" + date);
            }
        }).start();
    }

    public String formatDate(int second) {
        Date date = new Date(1000 * second);
        return format.format(date);
    }
}

class SafeThreadLocal {
    public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
        @Override
        public SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");
        }
    };
}
